<template>
	<view class="content">
		<view class="bag" style="background-image: url('../../static/image/home/login_bg.png');">
			<view class="header">
				<view class="denglu">欢迎登录</view>
				<input type="number" placeholder="请输入手机号" class="zh" v-model="mobile">
				<view class="header_a flexbetween">
					<input type="number" placeholder="请输入手机验证码" class="mm" v-model="captcha">
					<view class="huoqu" @click="sendcode">{{codetext}}</view>
				</view>
				<view class="yue flexleft" @click="changeclick">
					<image src="/static/image/home/wiexuanzhong.png" mode="" class="dui" v-show="!quan"></image>
					<image src="/static/image/home/xuanzhong.png" mode="" class="dui" v-show="quan"></image>
					<view class=""> 阅读并同意<text class="orange" @click.stop="toyonghuxy">《用户协议》</text>和<text
							class="orange" @click.stop="toyinsi">《隐私保护政策》</text></view>
				</view>
				<view class="dl" @click="thelogin">同意协议并登录</view>
			</view>
			<view class="otherBox">
				<view class="otherBoxTop">
					<view class="line margin_right2"></view>
					<view class="text">其它方式登录</view>
					<view class="line margin_left2"></view>
				</view>
				<view class="otherBoxBottom">
					<view class="weixin" @click="wxLogin">
						<image src="/static/image/home/weixin.png" mode="widthFix"></image>
						<view class="text">微信登录</view>
					</view>
					<view class="qq" @click="qqLogin">
						<image src="/static/image/home/QQ.png" mode="widthFix"></image>
						<view class="text">QQ登录</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const httpRequest = require("@/common/httpRequest.js")
	// #ifdef APP-PLUS
	const TUICallKit = uni.requireNativePlugin('TencentCloud-TUICallKit');
	// #endif
	import WebSocket from '@/common/websocket.js' //websocket封装
	export default {
		data() {
			return {
				quan: false,
				eys: false,
				// captcha: '1234',
				// mobile: '13888888888',
				captcha: '',
				mobile: '',
				codetext: "获取验证码",
				loginType: 0, //登录方式 1微信 2QQ
				websocket:null
			}
		},
		onLoad() {

		},
		methods: {
			shouquan() {
				uni.navigateTo({
					url: "/pages/login/wangjimm"
				})
			},
			changeclick() {
				this.quan = this.quan ? false : true
			},
			// 发送验证码
			sendcode() {
				let _this = this
				let mobile = _this.mobile;
				if (!mobile.match(/^1\d{10}$/)) {
					httpRequest.toast("请输入有效的手机号码");
					return false;
				}
				httpRequest.request('/api/sms/send', 'POST', {
					mobile: mobile,
					event: "mobilelogin"
				}).then(resp => {
					if (resp.code == 1) {
						var i = 60;
						var timer = setInterval(function() {
							_this.codetext = i + "秒";
							if (i < 1) {
								clearInterval(timer);
								_this.codetext = "获取验证码";
							} else {
								i--;
							}
						}, 1000)

					} else if (resp.code == 0) {
						httpRequest.toast(resp.msg);
					} else {
						httpRequest.toast('网络开小差啦');
					}
				})
			},
			thelogin() {
				let _this = this
				let mobile = _this.mobile;
				let captcha = _this.captcha
				if (mobile == '') {
					httpRequest.toast('请输入手机号');
					return false;
				}
				if (!mobile.match(/^1\d{10}$/)) {
					httpRequest.toast("请输入有效的手机号码");
					return false;
				}
				if (captcha == "") {
					httpRequest.toast('请输入验证码');
					return false;
				}
				if (!_this.quan) {
					httpRequest.toast('请仔细阅读用户协议并勾选');
					return false;
				}
				this.checkCaptcha()
				// this.mobileLogin()
			},
			// 检测验证码
			checkCaptcha() {
				let mobile = this.mobile;
				if (!mobile.match(/^1\d{10}$/)) {
					httpRequest.toast("请输入有效的手机号码");
					return false;
				}
				if (this.captcha == "") {
					httpRequest.toast("请输入验证码");
					return false;
				}
				httpRequest.request('/api/sms/check', 'POST', {
					mobile: mobile,
					event: "mobilelogin",
					captcha: this.captcha
				}).then(resp => {
					if (resp.code == 1) {
						this.mobileLogin()
					} else {
						httpRequest.toast(resp.msg);
					}
				})
			},
			// 验证成功走登录接口
			mobileLogin() {
				let mobile = this.mobile;
				let _this = this
				httpRequest.request('/api/user/mobilelogin', 'POST', {
					mobile: mobile,
					captcha: this.captcha,
					appform: 1
				}).then(resp => {
					if (resp.code == 1) {
						httpRequest.toast(resp.msg);
						setTimeout(() => {
							uni.switchTab({
								url: uni.getStorageSync('jumpPath')
							})
						}, 500)
						let userinfo = resp['data']['userinfo'];
						uni.setStorageSync('token', userinfo['token']);
						uni.setStorageSync('user_id', userinfo['user_id']);
						this.websocketStart()
						uni.getPushClientId({
							success: (res) => {
								_this.setcidbindalias(res.cid,'yh'+userinfo['user_id'])
							}
						});
						this.getUserInfo(userinfo['user_id'])
					}
					if (resp.code == 0) {
						httpRequest.toast(resp.msg);
					}
				})
			},
			websocketStart() {
				this.websocket = new WebSocket("wss://chat.hongniaotianxuan.com:8282");
				this.websocket.connect()
				this.websocket.onMessage(result => {
					console.log('app.js收到服务器内容：' +result.data);
					uni.$emit('updatechatFn', "")
					uni.$emit('updatechatFnList', "")
				})
			},
			// 绑定推送别名
			setcidbindalias(cid,alias){
				console.log("綁定推送別名開始",cid,alias);
				uni.request({
					url: "https://fc-mp-0ae3b67a-cfa0-4720-ac2b-11ceed2b7c57.next.bspapp.com/biemingxg",
					data: {
						cids:cid,
						alias:alias
					},
					header: {
						'content-type': "application/json",
					},
					method: "POST", //'GET','POST'
					dataType: 'json',
					success: (res) => {
						console.log("绑定推送别名请求成功", res);
					}
				})
			},
			getUserInfo(user_id) {
				let _this = this
				httpRequest.request('/api/user/index', 'GET', {

				}).then(resp => {
					if (resp.code == 1) {
						// #ifdef APP-PLUS
						console.log("app11111111111111111111")
						console.log(resp)
						_this.tuicallkitLogin(user_id, resp.data.UserSig) //即时通讯im音视频语音
						// #endif
					}
					if (resp.code == 0) {
						httpRequest.toast(resp.msg);
					}
				})
			},
			tuicallkitLogin(userId, userSig) {
				// console.log(11111111111111111111111111111111111)
				// console.log(userId)
				console.log(userId, userSig, "555555555555555555555555555")
				const options = {
					SDKAppID: 1400822265, // 请替换为步骤一取到的 SDKAppID
					userID: userId, // 请替换为您的 UserID
					userSig: userSig, // 您可以在控制台中计算一个 UserSig 并填在这个位置
				};
				TUICallKit.login(options, (res) => {
					if (res.code === 0) {
						console.log('login success');
					} else {
						console.log(`login failed, error message = ${res.msg}`);
					}
				});
			},
			//跳转用户协议
			toyonghuxy() {
				uni.navigateTo({
					url: '/pages_mine/aboutWe?type=2'
				})
			},
			//跳转隐私政策
			toyinsi() {
				uni.navigateTo({
					url: '/pages_mine/aboutWe?type=3'
				})
			},
			wxLogin() { //微信登录
				let _this = this
				_this.loginType = 1
				if (!_this.quan) {
					httpRequest.toast('请仔细阅读用户协议并勾选');
					return false;
				}
				let parameters = {
					code: "",
					appform: 1,
				}
				uni.login({
					provider: 'weixin',
					onlyAuthorize: true,
					success: function(loginRes) {
						console.log(JSON.stringify(loginRes), 'loginRes');
						// return false
						parameters.code = loginRes.code
						// 登录成功
						_this.getLogin(parameters, "wx")
					},
					fail: function(err) {
						console.log(err, 'qq授权失败');
						// 登录授权失败  
						// err.code是错误码
					}
				});
			},
			qqLogin() { //qq登录
				let _this = this
				_this.loginType = 2
				if (!_this.quan) {
					httpRequest.toast('请仔细阅读用户协议并勾选');
					return false;
				}
				let parameters = {
					openId: '',
					unionid: '',
					access_token: '',
					appform: 1,
					nickName: '',
					avatarUrl: '',
					gender: '',
				}
				uni.login({
					provider: 'qq',
					success: function(loginRes) {
						console.log(JSON.stringify(loginRes), 'loginRes');
						parameters.openId = loginRes.authResult.openid
						parameters.access_token = loginRes.authResult.access_token
						// 登录成功
						uni.getUserInfo({
							provider: 'qq',
							success: function(info) {
								// 获取用户信息成功, info.authResult保存用户信息
								console.log(JSON.stringify(info), 'info99999999');
								parameters.nickName = info.userInfo.nickName
								parameters.avatarUrl = info.userInfo.avatarUrl
								parameters.gender = info.userInfo.gender_type
								parameters.unionid = info.userInfo.unionid
								console.log(JSON.stringify(parameters));
								_this.getLogin(parameters, "qq")
							}
						})
					},
					fail: function(err) {
						console.log(err, 'qq授权失败');
						// 登录授权失败  
						// err.code是错误码
					}
				});
			},
			getLogin(userInfo, type) {
				let _this = this
				let url;
				if (this.loginType == 1) {
					url = "/api/user/wxlogin"
				} else {
					url = "/api/user/qqlogin"
				}
				// console.log(userInfo);
				httpRequest.request(url, 'POST', userInfo).then(resp => {
					// console.log(JSON.stringify(resp), "resp9999999999999999");
					console.log(resp, "resp9999999999999999");
					if (resp.code == 1) {
						if (resp.data.need_login_type == 1) { //登录成功
							httpRequest.toast(resp.msg);
							setTimeout(() => {
								uni.switchTab({
									url: "/pages/index/index"
								})
							}, 500)
							let userinfo = resp['data']['userinfo'];
							
							uni.setStorageSync('token', userinfo['token']);
							uni.setStorageSync('user_id', userinfo['user_id']);
							uni.getPushClientId({
								success: (res) => {
									_this.setcidbindalias(res.cid,'yh'+userinfo['user_id'])
								}
							});
							this.websocketStart()
							this.getUserInfo(userinfo['user_id'])
						} else { //需要绑定手机号
							console.log("需要绑定手机号！！！！！！");
							uni.redirectTo({
								url: `/pages/login/phoneLogin?platform=${type}&openid=` + resp.data.openid
							})
						}
					} else {
						httpRequest.toast(resp.msg);
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	input {
		height: inherit;
	}

	.img {
		width: 28rpx;
		height: 20.36rpx;
	}

	.huoqu {
		font-size: 30rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #F3271C;
		margin-right: 14rpx;
		min-width: 200rpx;
		text-align: right;
	}

	.orange {
		color: rgba(243, 39, 28, 1);
	}

	.bag {
		width: 100%;
		height: 100vh;
		background-size: 100% 100%;
	}


	.header_a {
		border-bottom: 1rpx solid rgba(153, 153, 153, 0.10);
	}

	.content {
		background-color: #ffffff;
		min-height: 80vh;
	}

	.header {
		padding: 0rpx 30rpx;
	}

	.denglu {
		padding-top: 208rpx;
		font-size: 40rpx;
		font-family: PingFang SC-Heavy, PingFang SC;
		font-weight: 800;
		color: #000000;
	}

	input:input-placeholder {
		color: #999999;
	}

	.zh {
		margin-top: 86rpx;
		padding-bottom: 28rpx;
		border-bottom: 1rpx solid rgba(153, 153, 153, 0.10);
		font-size: 28rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
	}

	.mm {
		flex: 1;
		margin-top: 44rpx;
		border-bottom: 1rpx solid rgba(153, 153, 153, 0.10);
		padding-bottom: 45rpx;
		font-size: 28rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
	}

	.yue {
		font-size: 28rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #999999;
		margin-top: 71rpx;
		margin-left: 10rpx;
		margin-right: 8rpx;
	}

	.dui {
		width: 26rpx;
		height: 26rpx;
		margin-right: 7rpx;
	}

	.dui1 {
		width: 23rpx;
		height: 23rpx;
		margin-right: 7rpx;
		border: 1rpx solid #999;
		border-radius: 50%;
	}

	.dl {
		margin-left: 10rpx;
		margin-right: 8rpx;
		margin-top: 30rpx;
		width: 672rpx;
		height: 82rpx;
		background-color: rgba(243, 39, 28, 1);
		font-size: 32rpx;
		border-radius: 41rpx 41rpx 41rpx 41rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #FFFFFF;
		line-height: 82rpx;
		text-align: center;
	}

	.otherBox {
		margin-top: 171rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.otherBoxTop {
		display: flex;
		align-items: center;

		.line {
			width: 38rpx;
			height: 0rpx;
			border: 1rpx solid #CCCCCC;
		}

		.text {
			font-size: 24rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 500;
			color: #999999;
		}
	}

	.otherBoxBottom {
		margin-top: 68rpx;
		display: flex;
		justify-content: center;
		text-align: center;

		image {
			width: 76rpx;
			height: 76rpx;
		}

		.weixin {
			margin-right: 126rpx;
		}

		.text {
			font-size: 24rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 500;
			color: #000000;
			margin-top: 20rpx;
		}

	}
</style>